const fs = require('fs-extra')
const argv = require('optimist').argv
const Redis = require('./libs/redis')
const Amqp = require('./libs/amqp')
const WS = require('./libs/ws')
const Common = require('./libs/common')
const Crypto = require('./libs/crypto')
const config = require(`./configs/${argv.dev ? 'development' : 'production'}`)

//如果控制台传入了p参数则采用该参数为端口号否则使用默认端口
const serverPort = argv.p || config.server.port

let amqpPool = {}
let redis = {}
let rdb = {}

//实例化工具类
const common = new Common({ config, fs })
//实例化加密类
const crypto = new Crypto({
	common,
	dataPrivateKey: fs.readFileSync('keys/cxxy_data_private.key', { encoding: 'utf-8' }),
	privateKey: fs.readFileSync('keys/cxxy_private.key', { encoding: 'utf-8' }),
	publicKey: fs.readFileSync('keys/cxxy_public.key', { encoding: 'utf-8' })
})

const dataKey = crypto.decryptDataKey(config.frame.dataKey)
const dataIv = crypto.decryptDataKey(config.frame.dataIv)

//连接所有需要连接的Redis数据库
for(let name in config.redis) {
	redis[name] = {}
	for(let item of ['get', 'set', 'delete', 'expire', 'find', 'trans', 'commit']) {
		redis[name][item] = async (...args) => {
			if(!rdb[name]) {
				rdb[name] = new Redis(common, name, config.redis[name], crypto, dataKey, dataIv)
			}
			console.log(name, item, ...args)
			return await rdb[name][item](...args)
		}
	}
}

//连接所有需要连接的RabbitMQ服务器
for(let connName in config.amqp) {
	amqpPool[connName] = new Amqp(common, config.amqp[connName])
}

//实例化WS服务器
const ws = new WS(common, config, redis, amqpPool)

//学生消息
ws.router('/message/student', async (ctx) => {
	const {userId} = ctx.user
	ctx.ch.receive(`student@${userId}`, (msg) => {
		const data = ctx.parseMsg(msg)
		if(!data)
			return
		console.log(data)
		ctx.resolve(data)
		ctx.ch.ok(msg)
	})
}, async (ctx) => {
	const data = ctx.parseMsg(ctx.msg)
	if(!data)
		return
	console.log(data)
})